package com.info.zhiduoduo.admin.service;

import com.baomidou.mybatisplus.mapper.Condition;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.info.zhiduoduo.admin.model.formbean.project.AddEditTemplateFormBean;
import com.info.zhiduoduo.admin.model.formbean.project.TemplateListFormBean;
import com.info.zhiduoduo.admin.model.formbean.system.*;
import com.info.zhiduoduo.common.constants.Constants;
import com.info.zhiduoduo.common.constants.SmartResult;
import com.info.zhiduoduo.common.constants.StatusMsg;
import com.info.zhiduoduo.common.constants.system.UserType;
import com.info.zhiduoduo.common.exception.Asserts;
import com.info.zhiduoduo.common.formbean.BaseAuthInfo;
import com.info.zhiduoduo.common.formbean.BaseSimpleFormBean;
import com.info.zhiduoduo.common.utils.DateUtil;
import com.info.zhiduoduo.common.utils.NumberUtil;
import com.info.zhiduoduo.common.utils.StringUtil;
import com.info.zhiduoduo.core.service.CoreSensitiveService;
import com.info.zhiduoduo.core.service.common.AuthService;
import com.info.zhiduoduo.core.service.common.BaseService;
import com.info.zhiduoduo.core.vo.auth.UserAuthVO;
import com.info.zhiduoduo.repository.dto.system.*;
import com.info.zhiduoduo.repository.entity.crm.CrmSystemDict;
import com.info.zhiduoduo.repository.entity.system.*;
import com.info.zhiduoduo.repository.mapper.system.*;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import javax.annotation.Resource;
import javax.validation.Valid;

@Transactional
@Service
public class SystemService extends BaseService {

    @Autowired
    AuthService authService;

    @Resource
    SystemCfgMapper systemCfgMapper;

    @Resource
    RoleMapper roleMapper;
    @Resource
    RoleMenuMapper roleMenuMapper;
    @Resource
    MenuMapper menuMapper;
    @Resource
    ManagerMapper managerMapper;
    @Resource
    ProjectCategoryMapper projectCategoryMapper;
    @Resource
    ProjectTempalteMapper projectTempalteMapper;
    @Resource
    TradeCategoryMapper tradeCategoryMapper;
    @Resource
    EnterpriseIndustryMapper industryMapper;

    @Resource
    InvoiceCategoryMapper invoiceCategoryMapper;

	@Resource
	CityInvoiceCategoryMapper cityInvoiceCategoryMapper;
    @Resource
    SensitiveVocabularyMapper sensitiveVocabularyMapper;

    @Resource
    CoreSensitiveService coreSensitiveService;


    /**
     * 添加角色
     *
     * @param formBean
     * @return
     */
    public SmartResult saveSystemRole(BaseSimpleFormBean<SaveSystemRoleFormBean> formBean) {
        SmartResult smartResult = new SmartResult();
        if (null == formBean) {
            smartResult.setStateMsg(StatusMsg.StatusMsg_101);
            return smartResult;
        }
        SaveSystemRoleFormBean saveSystemRoleFormBean = formBean.getReqdata();

        //校验角色名是否已存在
        int count = roleMapper.checkRole(saveSystemRoleFormBean.getRolename());
        if (count > 0) {
            smartResult.setStateMsg(StatusMsg.StatusMsg_199);
            smartResult.setMsg("角色名已存在");
            return smartResult;
        }
        //1.添加
        SystemRole systemRole = new SystemRole();
        BeanUtils.copyProperties(saveSystemRoleFormBean, systemRole);
        boolean save = systemRole.insert();
        if (!save) {
            smartResult.setStateMsg(StatusMsg.StatusMsg_199);
            return smartResult;
        }
        if (StringUtil.isNotEmpty(saveSystemRoleFormBean.getMenuids())) {
            String[] menuIds = saveSystemRoleFormBean.getMenuids().split(",");
            //2.添加角色关联的菜单
            roleMenuMapper.saveRoleMenu(systemRole.getRoleid(), menuIds);
        }

        return smartResult;
    }

    /**
     * 查看角色列表
     *
     * @return
     */
    public SmartResult querySystemRolePage() {
        SmartResult smartResult = new SmartResult();
        SystemRole systemRole = new SystemRole();
        List<SystemRole> systemRoleList = systemRole.selectAll();
        smartResult.setList(systemRoleList);

        return smartResult;
    }

    /**
     * 查询角色
     **/
    public SmartResult<SystemManager> getSystemManagerById(BaseSimpleFormBean formBean) {
        SystemManager newSystemManager = new SystemManager();
        newSystemManager.setManagerid(formBean.getUserid());
        SystemManager systemManager = newSystemManager.selectById();
    return  smartResult(systemManager);
    }

    /**
     * 查看角色详情
     *
     * @param formBean
     * @return
     */
    public SmartResult getSystemRoleById(BaseSimpleFormBean<GetSystemRoleFormBean> formBean) {
        SmartResult smartResult = new SmartResult();
        if (null == formBean) {
            smartResult.setStateMsg(StatusMsg.StatusMsg_101);
            return smartResult;
        }
        GetSystemRoleFormBean getSystemRoleFormBean = formBean.getReqdata();
        GetSystemRoleDto getSystemRoleDto = roleMapper.getSystemRoleById(getSystemRoleFormBean.getRoleid());
        smartResult.setObject(getSystemRoleDto);
        return smartResult;
    }

    /**
     * 删除角色
     *
     * @param formBean
     * @return
     */
    public SmartResult deleteSystemRole(BaseSimpleFormBean<GetSystemRoleFormBean> formBean) {
        SmartResult smartResult = new SmartResult();
        if (null == formBean) {
            smartResult.setStateMsg(StatusMsg.StatusMsg_101);
            return smartResult;
        }
        GetSystemRoleFormBean getSystemRoleFormBean = formBean.getReqdata();
        int roleId = getSystemRoleFormBean.getRoleid();
        //删除角色之前先判断是否被账户绑定
        int count = managerMapper.queryManagerCount(roleId);
        if (count > 0) {
            smartResult.setStateMsg(StatusMsg.StatusMsg_199);
            smartResult.setMsg("该角色已被" + count + "个账户绑定");
            return smartResult;
        }
        // 删除角色后 删除角色关联的菜单
        roleMenuMapper.deleteSystemRoleMenu(roleId);

        SystemRole systemRole = new SystemRole();
        boolean delete = systemRole.deleteById(roleId);

        return smartResult;
    }

    /**
     * 编辑角色
     *
     * @param formBean
     * @return
     */
    public SmartResult updateRole(BaseSimpleFormBean<UpdateSystemRoleFormBean> formBean) {
        SmartResult smartResult = new SmartResult();
        if (null == formBean) {
            smartResult.setStateMsg(StatusMsg.StatusMsg_101);
            return smartResult;
        }
        UpdateSystemRoleFormBean updateSystemRoleFormBean = formBean.getReqdata();
        String roleName = updateSystemRoleFormBean.getRolename();
        int roleId = updateSystemRoleFormBean.getRoleid();
        /**
         * 判空
         */
        if (StringUtil.isEmpty(roleName)) {
            smartResult.setStateMsg(StatusMsg.StatusMsg_199);
            smartResult.setMsg("角色名为空");
            return smartResult;
        }
        /**
         * 修改角色名
         */
        SystemRole systemSystemRole = new SystemRole();
        BeanUtils.copyProperties(updateSystemRoleFormBean, systemSystemRole);
        boolean update = systemSystemRole.updateById();
        /**
         * 将角色菜单删除
         */
        roleMenuMapper.deleteSystemRoleMenu(roleId);

        //添加角色菜单
        if (StringUtil.isNotEmpty(updateSystemRoleFormBean.getMenuids())) {
            String[] menuIds = updateSystemRoleFormBean.getMenuids().split(",");
            //2.添加角色关联的菜单
            roleMenuMapper.saveRoleMenu(systemSystemRole.getRoleid(), menuIds);
        }
        return smartResult;
    }

    /**
     * 获取菜单列表
     *
     * @param formBean
     * @return
     */
    public SmartResult getsystemMenus(BaseSimpleFormBean formBean) {
        return smartResult(getMenuChildrenList(0));
    }

    /**
     * 递归方法-获取菜单及其子菜单
     *
     * @param parentid
     * @return
     */
    private List<MenuDto> getMenuChildrenList(int parentid) {
        return menuMapper.getMenuChildrenList(parentid)
                .stream()
                .peek(menu -> menu.setChildren(getMenuChildrenList(menu.getMenuid())))
                .collect(Collectors.toList());
    }

    //----------账户---------

    /**
     * 添加账户
     *
     * @param formBean
     * @return
     */
    public SmartResult saveManager(BaseSimpleFormBean<SaveManagerFormBean> formBean) {
        SmartResult smartResult = new SmartResult();
        if (null == formBean) {
            smartResult.setStateMsg(StatusMsg.StatusMsg_101);
            return smartResult;
        }
        SaveManagerFormBean saveManagerFormBean = formBean.getReqdata();
        if (StringUtil.isEmpty(saveManagerFormBean.getLoginname())) {
            smartResult.setStateMsg(StatusMsg.StatusMsg_101);
            smartResult.setMsg("登录名不能为空");
            return smartResult;
        }
        //校验
        QueryManagerDto check = checkLoginName(saveManagerFormBean.getLoginname());
        if (null != check) {
            smartResult.setStateMsg(StatusMsg.StatusMsg_101);
            smartResult.setMsg("登录名已存在");
            return smartResult;
        }
        SystemManager systemManager = new SystemManager();
        BeanUtils.copyProperties(saveManagerFormBean, systemManager);
        systemManager.setState(1);//1正常 2冻结
        boolean save = systemManager.insert();
        if (!save) {
            smartResult.setStateMsg(StatusMsg.StatusMsg_199);
        }
        return smartResult;
    }

    /**
     * 查看账户列表
     *
     * @return
     */
    public SmartResult queryManagerPage() {
        SmartResult smartResult = new SmartResult();
        List<QueryManagerDto> queryManagerDtos = managerMapper.queryManagerPage();
        smartResult.setList(queryManagerDtos);
        return smartResult;
    }

    /**
     * 查看账户详情
     *
     * @param formBean
     * @return
     */
    public SmartResult getManagerById(BaseSimpleFormBean<GetManagerFormBean> formBean) {
        SmartResult smartResult = new SmartResult();
        if (null == formBean) {
            smartResult.setStateMsg(StatusMsg.StatusMsg_101);
            return smartResult;
        }
        GetManagerFormBean getManagerFormBean = formBean.getReqdata();
        QueryManagerDto queryManagerDto = managerMapper.getManagerById(getManagerFormBean.getManagerid());
        smartResult.setObject(queryManagerDto);
        return smartResult;
    }

    /**
     * 编辑账户
     *
     * @param formBean
     * @return
     */
    public SmartResult updateManager(BaseSimpleFormBean<UpdateManagerFormBean> formBean) {
        SmartResult smartResult = new SmartResult();
        if (null == formBean) {
            smartResult.setStateMsg(StatusMsg.StatusMsg_101);
            return smartResult;
        }

        UpdateManagerFormBean updateManagerFormBean = formBean.getReqdata();
        if (StringUtil.isEmpty(updateManagerFormBean.getLoginname())) {
            smartResult.setStateMsg(StatusMsg.StatusMsg_101);
            smartResult.setMsg("登录名不能为空");
            return smartResult;
        }
        //校验
        QueryManagerDto check = checkLoginName(updateManagerFormBean.getLoginname());
        if (null != check && check.getManagerid() != updateManagerFormBean.getManagerid()) {
            smartResult.setStateMsg(StatusMsg.StatusMsg_101);
            smartResult.setMsg("登录名已存在");
            return smartResult;
        }
        SystemManager systemManager = new SystemManager();
        BeanUtils.copyProperties(updateManagerFormBean, systemManager);
        boolean update = systemManager.updateById();
        if (!update) {
            smartResult.setStateMsg(StatusMsg.StatusMsg_199);
        }
        return smartResult;
    }

    /**
     * 删除账户
     *
     * @param formBean
     * @return
     */
    public SmartResult deleteManager(BaseSimpleFormBean<GetManagerFormBean> formBean) {
        SmartResult smartResult = new SmartResult();
        if (null == formBean) {
            smartResult.setStateMsg(StatusMsg.StatusMsg_101);
            return smartResult;
        }
        GetManagerFormBean getManagerFormBean = formBean.getReqdata();
        SystemManager systemManager = new SystemManager();
        boolean delete = systemManager.deleteById(getManagerFormBean.getManagerid());
        if (!delete) {
            smartResult.setStateMsg(StatusMsg.StatusMsg_199);
        }
        return smartResult;
    }

    /**
     * 登录
     *
     * @param formBean
     * @return
     */
    public SmartResult login(BaseSimpleFormBean<LoginFormBean> formBean) {
        SmartResult smartResult = new SmartResult();
        if (null == formBean) {
            smartResult.setStateMsg(StatusMsg.StatusMsg_101);
            return smartResult;
        }
        LoginFormBean loginFormBean = formBean.getReqdata();
        QueryManagerDto queryManagerDto = managerMapper.loginCheckPassword(loginFormBean.getLoginname(), loginFormBean.getPassword());
        if (null == queryManagerDto) {
            smartResult.setStateMsg(StatusMsg.StatusMsg_123);
            return smartResult;
        }
        if (queryManagerDto.getState() == 2) {
            smartResult.setStateMsg(StatusMsg.StatusMsg_123);
            smartResult.setMsg("账号被冻结");
            return smartResult;
        }
		/*
		// 从SecurityUtils里边创建一个 subject
		Subject subject = SecurityUtils.getSubject();
		// 在认证提交前准备 token（令牌）
		UsernamePasswordToken token = new UsernamePasswordToken(loginFormBean.getLoginname(), loginFormBean.getPassword());
		//返回参数
		QueryManagerDto queryManagerDto;
		// 执行认证登陆
		try {
			subject.login(token);
			long timeout = subject.getSession().getTimeout();
			queryManagerDto = managerMapper.login(loginFormBean.getLoginname());
			if(!StringUtils.isEmpty(subject.getSession().getId().toString())){
				queryManagerDto.setToken(subject.getSession().getId().toString());
			}
		} catch (LockedAccountException lae) {
			return returnValue(StateMsg.StatusMsg_129);
		} catch (ExcessiveAttemptsException eae) {
			return returnValue(304,"用户名或密码错误次数过多");
		} catch (AuthenticationException ae) {
			return returnValue(StateMsg.StatusMsg_115);
		}
		if (!subject.isAuthenticated()) {
			token.clear();
			return returnValue(StateMsg.StatusMsg_123);
		}
*/


/*		//获取菜单权限列表
		List<RoleMenuDto> roleMenuList = roleMenuMapper.getRoleMenuList(queryManagerDto.getRoleid());
		queryManagerDto.setMenuList(roleMenuList);*/

        authService.loginSuccess(UserAuthVO.of(queryManagerDto.getManagerid(), UserType.UNKOWN, new Date()));

        smartResult.setObject(queryManagerDto);
        return smartResult;
    }

    public SmartResult switchAdmin(BaseSimpleFormBean<SwitchFormBean> formBean) {
        SwitchFormBean reqdata = formBean.getReqdata();
        QueryManagerDto managerDto = managerMapper.checkLoginName(reqdata.getLoginname());
        if (managerDto == null) return SmartResult.fail(StatusMsg.StatusMsg_132);
        return SmartResult.success(managerDto);
    }

    /**
     * 账户冻结解冻
     *
     * @param formBean
     * @return
     */
    public SmartResult updateManagerState(BaseSimpleFormBean<UpdateManagerStateFormBean> formBean) {
        SmartResult smartResult = new SmartResult();
        if (null == formBean) {
            smartResult.setStateMsg(StatusMsg.StatusMsg_101);
            return smartResult;
        }
        UpdateManagerStateFormBean uodateFormBean = formBean.getReqdata();
        int update = managerMapper.updateManagerState(uodateFormBean.getManagerid(), uodateFormBean.getState());
        return smartResult;
    }

    //校验登录名
    public QueryManagerDto checkLoginName(String loginname) {
        return managerMapper.checkLoginName(loginname);
    }

    //----------------行业分类与经营范围 --------------

    /**
     * 1.添加一级的
     *
     * @param formBean
     * @return
     */
    public SmartResult saveTradecategoryOne(BaseSimpleFormBean<SaveTradecategoryOneFormBean> formBean) {
        SmartResult smartResult = new SmartResult();
        if (null == formBean) {
            smartResult.setStateMsg(StatusMsg.StatusMsg_101);
            return smartResult;
        }
        SaveTradecategoryOneFormBean saveTradecategoryOneFormBean = formBean.getReqdata();
        SystemTradeCategory systemTradeCategory = new SystemTradeCategory();
        BeanUtils.copyProperties(saveTradecategoryOneFormBean, systemTradeCategory);
        System.out.println(systemTradeCategory);
        boolean save = systemTradeCategory.insert();
        if (!save) {
            smartResult.setStateMsg(StatusMsg.StatusMsg_199);
        }
        return smartResult;
    }

    /**
     * 2.添加二级的
     *
     * @param formBean
     * @return
     */
    public SmartResult saveTradecategoryTwo(BaseSimpleFormBean<SaveTradecategoryTwoFormBean> formBean) {
        SmartResult smartResult = new SmartResult();
        if (null == formBean) {
            smartResult.setStateMsg(StatusMsg.StatusMsg_101);
            return smartResult;
        }
        SaveTradecategoryTwoFormBean saveTradecategoryTwoFormBean = formBean.getReqdata();
        SystemTradeCategory systemTradeCategory = new SystemTradeCategory();
        BeanUtils.copyProperties(saveTradecategoryTwoFormBean, systemTradeCategory);
        boolean save = systemTradeCategory.insert();
        if (!save) {
            smartResult.setStateMsg(StatusMsg.StatusMsg_199);
        }
        return smartResult;
    }

    /**
     * 3.查看一级的全部
     *
     * @return
     */
    public SmartResult queryTradecategoryOne() {
        SmartResult smartResult = new SmartResult();
        List<QuseryTradecategoryOneDto> quseryTradecategoryOneDtos = tradeCategoryMapper.queryTradecategoryOne();
        smartResult.setList(quseryTradecategoryOneDtos);
        return smartResult;
    }

    /**
     * 4.根据一级的id查看二级的
     *
     * @param formBean
     * @return
     */
    public SmartResult queryTradecategoryTwo(BaseSimpleFormBean<QuseryTradecategoryTwoFormBean> formBean) {
        SmartResult smartResult = new SmartResult();
        if (null == formBean) {
            smartResult.setStateMsg(StatusMsg.StatusMsg_101);
            return smartResult;
        }
        QuseryTradecategoryTwoFormBean quseryTradecategoryOneDto = formBean.getReqdata();
        List<QuseryTradecategoryTwoDto> quseryTradecategoryTwoDtos = tradeCategoryMapper.queryTradecategoryTwo(
                quseryTradecategoryOneDto.getParentid());
        smartResult.setList(quseryTradecategoryTwoDtos);
        return smartResult;
    }

    /**
     * 6.编辑一级的
     *
     * @param formBean
     * @return
     */
    public SmartResult updateTradecategoryOne(BaseSimpleFormBean<UpdateTradecategoryOneFormBean> formBean) {
        SmartResult smartResult = new SmartResult();
        if (null == formBean) {
            smartResult.setStateMsg(StatusMsg.StatusMsg_101);
            return smartResult;
        }
        UpdateTradecategoryOneFormBean updateTradecategoryOneFormBean = formBean.getReqdata();
        SystemTradeCategory systemTradeCategory = new SystemTradeCategory();
        BeanUtils.copyProperties(updateTradecategoryOneFormBean, systemTradeCategory);

        boolean update = systemTradeCategory.updateById();
        if (!update) {
            smartResult.setStateMsg(StatusMsg.StatusMsg_199);
        }
        return smartResult;
    }

    /**
     * 6.编辑二级的
     *
     * @param formBean
     * @return
     */
    public SmartResult updateTradecategoryTwo(BaseSimpleFormBean<UpdateTradecategoryTwoFormBean> formBean) {
        SmartResult smartResult = new SmartResult();
        if (null == formBean) {
            smartResult.setStateMsg(StatusMsg.StatusMsg_101);
            return smartResult;
        }
        UpdateTradecategoryTwoFormBean updateTradecategoryTwoFormBean = formBean.getReqdata();
        SystemTradeCategory systemTradeCategory = new SystemTradeCategory();
        BeanUtils.copyProperties(updateTradecategoryTwoFormBean, systemTradeCategory);
        boolean update = systemTradeCategory.updateAllColumnById();
        if (!update) {
            smartResult.setStateMsg(StatusMsg.StatusMsg_199);
        }
        return smartResult;
    }

    /**
     * 7.查看二级详情
     *
     * @param formBean
     * @return
     */
    public SmartResult getTradecategoryTwoById(BaseSimpleFormBean<GetTradecategoryTwoFormBean> formBean) {
        SmartResult smartResult = new SmartResult();
        if (null == formBean) {
            smartResult.setStateMsg(StatusMsg.StatusMsg_101);
            return smartResult;
        }
        GetTradecategoryTwoFormBean getTradecategoryTwoFormBean = formBean.getReqdata();
        SystemTradeCategory systemTradeCategory = new SystemTradeCategory();
        GetTradecategoryTwoDto getTradecategoryTwoDto = new GetTradecategoryTwoDto();
        systemTradeCategory = systemTradeCategory.selectById(getTradecategoryTwoFormBean.getTradecategoryid());
        BeanUtils.copyProperties(systemTradeCategory, getTradecategoryTwoDto);
        smartResult.setObject(getTradecategoryTwoDto);
        return smartResult;
    }

    /**
     * 删除二级的
     *
     * @param formBean
     * @return
     */
    public SmartResult deleteTradecategoryTwo(BaseSimpleFormBean<GetTradecategoryTwoFormBean> formBean) {
        SmartResult smartResult = new SmartResult();
        if (null == formBean) {
            smartResult.setStateMsg(StatusMsg.StatusMsg_101);
            return smartResult;
        }
        GetTradecategoryTwoFormBean getTradecategoryTwoFormBean = formBean.getReqdata();
        SystemTradeCategory systemTradeCategory = new SystemTradeCategory();
        boolean delete = systemTradeCategory.deleteById(getTradecategoryTwoFormBean.getTradecategoryid());
        if (!delete) {
            smartResult.setStateMsg(StatusMsg.StatusMsg_199);
        }
        return smartResult;
    }


    public SmartResult getTradeCategory(BaseAuthInfo baseAuthInfo) {
        SmartResult smartResult = new SmartResult();

        List<SystemTradeCategory> tradeCategoryList = tradeCategoryMapper.selectList(new EntityWrapper<SystemTradeCategory>());

        List<SystemTradeCategory> parentTradeCategoryList = new ArrayList<>();

        Map<Integer, List<SystemTradeCategory>> integerListMap = new HashMap<>();

        if (null != tradeCategoryList && tradeCategoryList.size() > 0) {
            for (SystemTradeCategory SystemTradeCategory : tradeCategoryList) {
                if (NumberUtil.safeInt(SystemTradeCategory.getParentid()) == 0) {
                    parentTradeCategoryList.add(SystemTradeCategory);
                } else {
                    List<SystemTradeCategory> childTradeCategory = integerListMap.get(SystemTradeCategory.getParentid());
                    if (null == childTradeCategory || childTradeCategory.size() == 0) {
                        childTradeCategory = new ArrayList<>();
                    }
                    childTradeCategory.add(SystemTradeCategory);
                    integerListMap.put(SystemTradeCategory.getParentid(), childTradeCategory);
                }
            }
        }

        for (SystemTradeCategory SystemTradeCategory : parentTradeCategoryList) {
            SystemTradeCategory.setChildTradeCategory(integerListMap.get(SystemTradeCategory.getTradecategoryid()));
        }

        smartResult.setList(parentTradeCategoryList);
        return smartResult;
    }

    public SmartResult addIndustry(BaseSimpleFormBean<AddIndustryFormBean> formBean) {
        @Valid AddIndustryFormBean reqdata = formBean.getReqdata();
        String industryName = reqdata.getIndustryName();
        int industryId = reqdata.getIndustryId();

        EnterpriseIndustry exist = industryMapper.findByName(industryName);
        if (exist != null) return SmartResult.fail(StatusMsg.StatusMsg_327);

        if (industryId == 0) {
            EnterpriseIndustry industry = new EnterpriseIndustry().setIndustryName(industryName);
            if (industry.insert()) {
                return SmartResult.success(industry.getIndustryId());
            }
        } else {
            EnterpriseIndustry industry = new EnterpriseIndustry().setIndustryId(industryId).setIndustryName(industryName);
            if (industry.updateById()) {
                return SmartResult.success(industry.getIndustryId());
            }
        }

        return SmartResult.ofOptFail();
    }

    public SmartResult delIndustry(BaseSimpleFormBean<Integer> formBean) {
        @Valid Integer industryId = formBean.getReqdata();
        new EnterpriseIndustry().deleteById(industryId);
        return SmartResult.success();
    }

    public SmartResult<EnterpriseIndustry> getIndustryList(BaseSimpleFormBean<String> formBean) {
        @Valid String name = formBean.getReqdata();
        List<EnterpriseIndustry> list = industryMapper.list(name);
        return SmartResult.success(list);
    }

    // --------------------- 项目分类管理 ---------------//

    /**
     * 获取所有一级项目分类及对应的二级列表
     *
     * @param formBean
     * @return
     */
    public SmartResult getAllProjectCategoryList(BaseSimpleFormBean formBean) {

        List<ProjectCategoryDto> list = projectCategoryMapper.getcategoryList(0);
        list.forEach(pc -> pc.setChildren(projectCategoryMapper.getcategoryList(pc.getProjectcategoryid())));

        return smartResult(list);
    }

    /**
     * 获取全部二级列表或指定parentid的二级列表
     *
     * @param formBean
     * @return
     */
    public SmartResult getTwoProjectCategoryList(BaseSimpleFormBean<Integer> formBean) {
        Integer parentid = formBean.getReqdata();
        if (parentid == null) parentid = 0;
        if (parentid == 0) {
            //获取全部二级列表
            Page<Object> page = PageHelper.startPage(formBean.getPage(), formBean.getRows());
            return smartResult(projectCategoryMapper.getAllLevelTwoList(), page.getTotal(), page.getPages(), page.getPageNum());
        } else {
            //获取指定parentid下的分类
            List<ProjectCategoryDto> list = projectCategoryMapper.getcategoryList(parentid);
            return smartResult(list);
        }
    }

    /**
     * 添加分类
     *
     * @param formBean
     * @return
     */
    public SmartResult addEditProjectCategory(BaseSimpleFormBean<AddProjectCategoryFormBean> formBean) {
        AddProjectCategoryFormBean reqdata = formBean.getReqdata();
        if (reqdata == null) return errorParamSmartResult();

        int parentid = reqdata.getParentid();
        int projectcategoryid = reqdata.getProjectcategoryid();
        String name = reqdata.getProjectcategory();
        if (projectcategoryid > 0) {
            //编辑
            SystemProjectcategory projectcategory = new SystemProjectcategory();
            BeanUtils.copyProperties(reqdata, projectcategory);
            projectcategory.updateById();
            return smartResult();

        }

        int count = new SystemProjectcategory().selectCount(Condition.create().eq("parentid", parentid).eq("projectcategory", name));
        if (count > 0) {
            return smartResult(StatusMsg.StatusMsg_125);
        }

        SystemProjectcategory projectcategory = new SystemProjectcategory();
        projectcategory.setParentid(parentid);
        projectcategory.setProjectcategory(name);
        projectcategory.setSort(reqdata.getSort());
        if (projectcategory.insert()) {
            return smartResult(projectcategory.getProjectcategoryid());
        }
        return optFailSmartResult();
    }

    /**
     * 删除项目分类
     */
    public SmartResult deleteProjectCategory(BaseSimpleFormBean<Integer> formBean) {
        Integer projectcategoryid = formBean.getReqdata();
        if (NumberUtil.isNotAllPositive(projectcategoryid)) {
            return errorParamSmartResult();
        }

        new SystemProjectcategory().deleteById(projectcategoryid);

        return smartResult();
    }


    /**
     * 新增编辑项目模板
     */
    public SmartResult addEditProjectTemplate(BaseSimpleFormBean<AddEditTemplateFormBean> formBean) {
        AddEditTemplateFormBean reqdata = formBean.getReqdata();
        if (reqdata == null) return errorParamSmartResult();
        if (reqdata.getCategoryid() <= 0 || StringUtil.isAnyEmpty(reqdata.getProjectname(), reqdata.getProjectintro()))
            return errorParamSmartResult();

        String checkResult = coreSensitiveService.checkSensitiveWords(reqdata.getProjectname(), reqdata.getProjectintro());
        Asserts.isBlank(checkResult, StatusMsg.StatusMsg_144);

        ProjectTemplate projectTemplate = new ProjectTemplate();
        BeanUtils.copyProperties(reqdata, projectTemplate);

        if (projectTemplate.insertOrUpdate()) return smartResult(projectTemplate.getId());
        else return optFailSmartResult();
    }

    /**
     * 获取模板列表
     */
    public SmartResult getProjectTemplateList(BaseSimpleFormBean<TemplateListFormBean> formBean) {
        TemplateListFormBean reqdata = formBean.getReqdata();
        if (reqdata == null) return errorParamSmartResult();

        int categoryid = reqdata.getCategoryid();
        String name = reqdata.getName();

        Page<Object> page = PageHelper.startPage(formBean.getPage(), formBean.getRows());
        List<ProjectTemplate> list = projectTempalteMapper.getTemplateList(categoryid, name);

        return smartResultPage(page);
    }

    /**
     * 删除项目模板
     */
    public SmartResult delProjectTemplate(BaseSimpleFormBean<Integer> formBean) {
        Integer id = formBean.getReqdata();
        if (id == null || id <= 0) return errorParamSmartResult();

        new ProjectTemplate().deleteById(id);
        return smartResult();
    }

    public SmartResult<EnterpriseIndustry> getEnterpriseIndustryList() {
        return SmartResult.success(new EnterpriseIndustry().selectAll());
    }

    public SmartResult<Map<Integer, List<CrmSystemDict>>> CrmSystemDictList(String typies) {
        Map<Integer, List<CrmSystemDict>> map = Stream.of(typies.split(","))
                .flatMap(type -> new CrmSystemDict().selectList(Condition.create().eq("dict_type", type)).stream())
                .collect(Collectors.groupingBy(CrmSystemDict::getDictType));
        return SmartResult.success(map);
    }


    /**
     * 添加 一级分类 开票内容
     *
     * @param baseSimpleFormBean
     * @return
     */
    public SmartResult saveInvoiceCategoryOne(BaseSimpleFormBean<SaveInvoiceCategoryFormBean> baseSimpleFormBean) {

        SaveInvoiceCategoryFormBean formBean = baseSimpleFormBean.getReqdata();
        if (formBean.getCompid() == null) return errorParamSmartResult();

        InvoiceCategory invoiceCategory = new InvoiceCategory();
        BeanUtils.copyProperties(formBean, invoiceCategory);
        invoiceCategory.setParentid(0);
        invoiceCategory.setCreatetime(new Date());
        invoiceCategory.setUpdatetime(new Date());
        invoiceCategory.setDeleted(0);

        if (invoiceCategory.insert()) return smartResult();

        return optFailSmartResult();

    }


    /**
     * 添加 二级分类 开票内容
     *
     * @param baseSimpleFormBean
     * @return
     */
    public SmartResult saveInvoiceCategoryTwo(BaseSimpleFormBean<SaveInvoiceCategoryTwoFormBean> baseSimpleFormBean) {

        SaveInvoiceCategoryTwoFormBean formBean = baseSimpleFormBean.getReqdata();

        InvoiceCategory invoiceCategory = new InvoiceCategory();
        BeanUtils.copyProperties(formBean, invoiceCategory);
        invoiceCategory.setCreatetime(new Date());
        invoiceCategory.setUpdatetime(new Date());
        invoiceCategory.setDeleted(0);

        if (invoiceCategory.insert()) return smartResult();
        return optFailSmartResult();
    }


    /**
     * 查询 一级分类列表
     *
     * @param baseSimpleFormBean
     * @return
     */
    public SmartResult<InvoiceCategoryOneDto> queryInvoiceCategoryOneList(BaseSimpleFormBean<QueryInvoiceCategoryFormBean> baseSimpleFormBean) {

        QueryInvoiceCategoryFormBean formBean = baseSimpleFormBean.getReqdata();
        String whereStr = "";

        if (formBean != null) {
            // 根据 公司查询
            if (!StringUtil.isEmpty(formBean.getCompanyName())) {
                whereStr += " c.compname like '%" + formBean.getCompanyName() + "%' ";
            }
            // 根据 分类名称查询
            if (!StringUtil.isEmpty(formBean.getCategoryName())) {
                whereStr += " i.name  like '%" + formBean.getCategoryName() + "%' ";
            }
        }

        Page<InvoiceCategoryOneDto> page = PageHelper.startPage(baseSimpleFormBean.getPage(), baseSimpleFormBean.getRows());
        List<InvoiceCategoryOneDto> list = invoiceCategoryMapper.queryInvoiceCategoryOneList(whereStr);

        return smartResult(list, page.getTotal(), page.getPages(), page.getPageNum());
    }

    /**
     * 根据 一级分类id 查询 二级列表
     *
     * @param baseSimpleFormBean
     * @return
     */
    public SmartResult queryInvoiceCategoryTwo(BaseSimpleFormBean<QueryInvoiceCategoryTwoFormBean> baseSimpleFormBean) {

        int parenid = baseSimpleFormBean.getReqdata().getParentid();

        List<InvoiceCategory> categoryList = new InvoiceCategory().selectList(Condition.create().eq("parentid", parenid).eq("deleted", 0));

        return smartResult(categoryList);
    }


    /**
     * 修改 一级/二级 分类
     *
     * @param baseSimpleFormBean
     * @return
     */
    public SmartResult updateInvoiceCategory(BaseSimpleFormBean<UpdateInvoiceCategoryFormBean> baseSimpleFormBean) {

        UpdateInvoiceCategoryFormBean formBean = baseSimpleFormBean.getReqdata();

        InvoiceCategory invoiceCategory = new InvoiceCategory().selectById(formBean.getInvoiceCategoryId());

        if (invoiceCategory == null) return smartResult(StatusMsg.StatusMsg_102);

        BeanUtils.copyProperties(formBean, invoiceCategory);

        if (!invoiceCategory.updateById()) return optFailSmartResult();

        return smartResult();
    }


    /**
     * 根据分类id 查询详情
     *
     * @param baseSimpleFormBean
     * @return
     */
    public SmartResult getInvoiceCategoryTwoById(BaseSimpleFormBean<CategoryIdFormBean> baseSimpleFormBean) {

        int id = baseSimpleFormBean.getReqdata().getInvoiceCategoryId();

        InvoiceCategory invoiceCategory = new InvoiceCategory().selectById(id);

        if (invoiceCategory == null) return smartResult(StatusMsg.StatusMsg_102);

        return smartResult(invoiceCategory);
    }


    /**
     * 删除 二级分类
     *
     * @param baseSimpleFormBean
     * @return
     */
    public SmartResult deleteInvoiceCategoryTwo(BaseSimpleFormBean<CategoryIdFormBean> baseSimpleFormBean) {
        int id = baseSimpleFormBean.getReqdata().getInvoiceCategoryId();
        boolean flag = new InvoiceCategory().deleteById(id);
        if (!flag) return optFailSmartResult();
        return smartResult();
    }


    public SmartResult queryAllInvoiceCategory(BaseSimpleFormBean<InvoiceCategoryFormBean> baseSimpleFormBean) {

        InvoiceCategoryFormBean formBean = baseSimpleFormBean.getReqdata();

        Integer partyId = formBean.getPartyId();
        String categoryName = formBean.getCategoryName();
			/*Condition condition = new Condition( InvoiceCategory.class );
			condition.eq("deleted", 0);
			if( partyId != null ){
				condition.and().eq("compid", partyId);
			}
			if( StringUtils.isNotEmpty(categoryName) ){
				condition.and().like("name", categoryName);
			}*/
        // 获取 一级列表
        List<InvoiceCategoryDto> categoryList = invoiceCategoryMapper.selectInvoiceCategoryList(partyId, categoryName);

        // 获取 二级列表
        categoryList.forEach((categoryDto) -> {
            categoryDto.setInvoiceCategoryDtoList(invoiceCategoryMapper.selectInvoiceCategoryByTwoList(categoryDto.getInvoiceCategoryId()));
        });

		return smartResult( categoryList );
	}

	// ===============    城市 开票类目      ==============

	/**
	 * 添加 一级分类 开票类目
	 * @param baseSimpleFormBean
	 * @return
	 */
	public SmartResult saveCityCategoryOne(BaseSimpleFormBean<SaveCityCategoryFormBean> baseSimpleFormBean) {

		SaveCityCategoryFormBean formBean = baseSimpleFormBean.getReqdata();
		if( formBean.getCityId() == null ) return errorParamSmartResult();
        List<CityInvoiceCategory> cityCategorys  = new CityInvoiceCategory().selectList(Condition.create().eq("city_id", formBean.getCityId()));
        for (CityInvoiceCategory list:cityCategorys){
            if (list.getName().equals(formBean.getName())){
                return smartResult(StatusMsg.StatusMsg_208);
            }
        }

		CityInvoiceCategory cityCategory = new CityInvoiceCategory();
		BeanUtils.copyProperties(formBean, cityCategory);
		cityCategory.setParentid(0);
		cityCategory.setUpdatetime( new Date() );
		cityCategory.setCreatetime( new Date());
		cityCategory.setDeleted(0);

		if( cityCategory.insert() ) return smartResult();

		return optFailSmartResult();

	}


	/**
	 * 添加 二级分类 开票内容
	 * @param baseSimpleFormBean
	 * @return
	 */
	public SmartResult saveCityCategoryTwo(BaseSimpleFormBean<SaveCityCategoryTwoFormBean> baseSimpleFormBean) {

		SaveCityCategoryTwoFormBean formBean = baseSimpleFormBean.getReqdata();
        List<CityInvoiceCategory> cityCategorys  = new CityInvoiceCategory().selectList(Condition.create().eq("parentid", formBean.getParentid()));
        for (CityInvoiceCategory list:cityCategorys){
            if (list.getName().equals(formBean.getName())){
                return smartResult(StatusMsg.StatusMsg_208);
            }
        }
		CityInvoiceCategory invoiceCategory = new CityInvoiceCategory();
		BeanUtils.copyProperties(formBean, invoiceCategory);
		invoiceCategory.setCreatetime( new Date());
		invoiceCategory.setUpdatetime( new Date() );
		invoiceCategory.setDeleted(0);

		if( invoiceCategory.insert() ) return smartResult();
		return optFailSmartResult();
	}


	/**
	 * 修改 一级/二级 分类
	 * @param baseSimpleFormBean
	 * @return
	 */
	public SmartResult updateCityCategory(BaseSimpleFormBean<UpdateCityCategoryFormBean> baseSimpleFormBean) {

		UpdateCityCategoryFormBean formBean = baseSimpleFormBean.getReqdata();

		CityInvoiceCategory invoiceCategory = new CityInvoiceCategory().selectById(formBean.getId());

		if( invoiceCategory == null ) return smartResult(StatusMsg.StatusMsg_102);

		if (invoiceCategory.getName().equals(formBean.getName()))return smartResult(StatusMsg.StatusMsg_208);

		BeanUtils.copyProperties(formBean, invoiceCategory);

		if( !invoiceCategory.updateById()  ) return optFailSmartResult();

		return smartResult();
	}

	/**
	 * 删除 一/二级 分类
	 * @param baseSimpleFormBean
	 * @return
	 */
	public SmartResult deleteCityCategory(BaseSimpleFormBean<Integer> baseSimpleFormBean) {
		int id = baseSimpleFormBean.getReqdata();
		boolean flag = new CityInvoiceCategory().deleteById(id);
		if( !flag ) return optFailSmartResult();
		return smartResult();
	}

	/**
	 * 查询 一二级 列表
	 * @param baseSimpleFormBean
	 * @return
	 */
	public SmartResult queryAllCityCategory(BaseSimpleFormBean<CityCategoryFormBean> baseSimpleFormBean) {
		CityCategoryFormBean formBean = baseSimpleFormBean.getReqdata();
		Integer cityId = formBean.getCityId();
		String categoryName = formBean.getCategoryName();
		// 获取 一级列表
		List<CityCategoryDto> categoryList = cityInvoiceCategoryMapper.selectCityCategoryList(cityId , categoryName);
		// 获取 二级列表
		categoryList.forEach((categoryDto) -> {
			categoryDto.setInvoiceCategoryDtoList(  cityInvoiceCategoryMapper.selectCityCategoryByTwoList( categoryDto.getId() )   );
		}  );
		return smartResult( categoryList );
	}


	/**
	 * 查询 一级分类列表
	 * @param baseSimpleFormBean
	 * @return
	 */
	public SmartResult<CityCategoryOneDto> queryCityCategoryOneList(BaseSimpleFormBean<QueryCityCategoryFormBean> baseSimpleFormBean) {

		QueryCityCategoryFormBean formBean = baseSimpleFormBean.getReqdata();
		String whereStr = "";

		if( formBean != null ){
			// 根据 公司查询
			if( !StringUtil.isEmpty(  formBean.getCityName() ) ){
				whereStr += " AND cc.name like '%"+formBean.getCityName()+"%' ";
			}
			// 根据 分类名称查询
			if( !StringUtil.isEmpty( formBean.getCategoryName() ) ){
				whereStr += " AND sc.name  like '%"+formBean.getCategoryName()+"%' ";
			}
		}

		Page<CityCategoryOneDto> page = PageHelper.startPage(baseSimpleFormBean.getPage(), baseSimpleFormBean.getRows());
		List<CityCategoryOneDto> list = cityInvoiceCategoryMapper.queryCityCategoryOneList(whereStr);

		return smartResult(list , page.getTotal() , page.getPages() , page.getPageNum() );
	}


	/**
	 * 根据 一级分类id 查询 二级列表
	 * @param baseSimpleFormBean
	 * @return
	 */
	public SmartResult queryCityCategoryTwo(BaseSimpleFormBean<Integer> baseSimpleFormBean) {

		int parenid = baseSimpleFormBean.getReqdata();

		List<CityInvoiceCategory> categoryList = new CityInvoiceCategory().selectList(Condition.create().eq("parentid", parenid).eq("deleted", 0));

		return smartResult(categoryList);
	}
	//查询敏感词
    public SmartResult sensitiveVocabularyList(BaseSimpleFormBean<String> formBean) {
	    //获取迷糊查询的数据
        String sensitivewords = formBean.getReqdata();
        //查询列表
        Page<Object> page = PageHelper.startPage(formBean.getPage(), formBean.getRows());
        List<SensitiveVocabularyDto> sensitiveVocabularyDto = sensitiveVocabularyMapper.sensitiveVocabularyList(sensitivewords);
        //二级分类
        for (SensitiveVocabularyDto list:sensitiveVocabularyDto){
            list.setSensitiveVocabularyDto(sensitiveVocabularyMapper.getSecondary(list.getId()));
        }

        return smartResultPage(page);
    }
    //一级敏感词 添加和修改敏感词
    public SmartResult addSensitiveVocabulary(BaseSimpleFormBean<SensitiveVocabularyFromBean> formBean){
	    SensitiveVocabularyFromBean reqdata = formBean.getReqdata();
        String sensitivewords =reqdata.getSensitiVewords();
	    //判断参数
	    if (sensitivewords == null || sensitivewords == "" )return errorParamSmartResult();
	    //判断敏感词是否存在
        List<SensitiveVocabulary> list = new SensitiveVocabulary().selectAll();
        for (SensitiveVocabulary sensitiveVocabulary : list ){
            if(sensitiveVocabulary.getSensitiveWords().equals(sensitivewords)){
                return smartResult(StatusMsg.StatusMsg_208);
            }
        }

	    //如果id传过来是空或者是0就添加
        if (reqdata.getId() == null || reqdata.getId() == 0 ){
            SensitiveVocabulary sensitiveVocabulary = new SensitiveVocabulary()
                    .setSensitiveWords(reqdata.getSensitiVewords())
                    .setParentid(0);
            if(!sensitiveVocabulary.insert())return smartResult(StatusMsg.StatusMsg_199);
        }else {
            //修改
            SensitiveVocabulary sensitiveVocabulary = new SensitiveVocabulary().selectById(formBean.getReqdata().getId());
            //判断数据库里是否有要修改的数据
            if(null == sensitiveVocabulary)return emptyDataSmartResult();
            sensitiveVocabulary.setSensitiveWords(sensitivewords).updateById();
        }
        return smartResult();
    }
    //删除敏感词
    public SmartResult deleteSensitiveVocabulary(BaseSimpleFormBean<Integer> formBean){
        Integer id= formBean.getReqdata();
        if (null == id || 0 == id) {
            return errorParamSmartResult();}
        //查询要删除的id是否存在
        SensitiveVocabulary sensitiveVocabulary = new SensitiveVocabulary().selectById(id);
        if(sensitiveVocabulary == null)return smartResult(StatusMsg.StatusMsg_199);
        sensitiveVocabulary.deleteById();
        return smartResult();
    }
    //二级敏感词 添加和修改敏感词
    public SmartResult addSecondarySensitiveWords(BaseSimpleFormBean<AddSecondarySensitiveWordsFromBean> formBean){
        AddSecondarySensitiveWordsFromBean reqdata = formBean.getReqdata();
        String sensitivewords =reqdata.getSensitiVewords();
        //判断敏感词是否存在
        List<SensitiveVocabulary> list = new SensitiveVocabulary().selectList(Condition.create().eq("parentid", reqdata.getParentid()));
        for (SensitiveVocabulary sensitiveVocabulary : list ){
            if(sensitiveVocabulary.getSensitiveWords().equals(sensitivewords)){
                return smartResult(StatusMsg.StatusMsg_208);
            }
        }

        //如果id传过来是空或者是0就添加
        if (reqdata.getId() == null || reqdata.getId() == 0 ){
            SensitiveVocabulary sensitiveVocabulary = new SensitiveVocabulary()
                    .setSensitiveWords(reqdata.getSensitiVewords())
                    .setParentid(reqdata.getParentid());
            if(!sensitiveVocabulary.insert())return smartResult(StatusMsg.StatusMsg_199);
        }else {
            //修改
            SensitiveVocabulary sensitiveVocabulary = new SensitiveVocabulary().selectById(formBean.getReqdata().getId());
            //判断数据库里是否有要修改的数据
            if(null == sensitiveVocabulary)return emptyDataSmartResult();
            sensitiveVocabulary.setSensitiveWords(sensitivewords).updateById();
        }
        return smartResult();
    }

    /**
     * 查看系统限制交易的时间段
     * @return
     */
    public SmartResult queryRestraintTradeTime(){
        SystemCfg start = new SystemCfg().selectById(Constants.RESTRAINT_TRADE_START);
        SystemCfg end = new SystemCfg().selectById(Constants.RESTRAINT_TRADE_END);
        if(start != null && end != null){
            return smartResult(start.getCfgValue() + "-" + end.getCfgValue());
        }
        return emptyDataSmartResult();
    }

    public SmartResult editRestraintTradeTime(EditRestraintTradeFormBean formBean){
        Date start = DateUtil.formatDate(formBean.getRestraintTradeStart(), DateUtil.FORMAT_STYLE_14);
        Date end = DateUtil.formatDate(formBean.getRestraintTradeEnd(), DateUtil.FORMAT_STYLE_14);
        if (start == null || end == null) {
            return smartResult(StatusMsg.StatusMsg_145);
        }
        if (start.getTime() > end.getTime()) {
            return smartResult(StatusMsg.StatusMsg_101);
        }
        SystemCfg startCfg = new SystemCfg();
        startCfg.setCfgKey(Constants.RESTRAINT_TRADE_START);
        startCfg.setCfgValue(DateUtil.DateToStr(DateUtil.FORMAT_STYLE_14, start));
        startCfg.updateById();

        SystemCfg endCfg = new SystemCfg();
        endCfg.setCfgKey(Constants.RESTRAINT_TRADE_END);
        endCfg.setCfgValue(DateUtil.DateToStr(DateUtil.FORMAT_STYLE_14, end));
        endCfg.updateById();
        return smartResult();
    }

}
